﻿using System;

using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class UGUIMultiClickButton : MonoBehaviour, IPointerClickHandler
{
    public Action<object> onSingleClickEvent;
    public Action<object> onDoubleClickEvent;
    public Action<object, int> onMultiClickEvent;

    [SerializeField]
    public float clickInterval = 0.25f;

    [SerializeField]
    public int maxClickCount = 2;

    [SerializeField]
    public bool ignoreTimeScale = true;

    private int _clickCount;
    private float _lastClickTime;

    void OnDisable()
    {
        _clickCount = 0;
    }

    void Update()
    {
        if (_clickCount == 0)
        {
            return;
        }

        var time = GetTime();

        if ((time - _lastClickTime > clickInterval)
            || (_clickCount >= maxClickCount))
        {
            switch (_clickCount)
            {
                case 1:
                    //Debug.LogWarning("[UGUIMultiClickButton]: OnSingleClickEvent");
                    if (onSingleClickEvent != null) { onSingleClickEvent(this); }
                    break;

                case 2:
                    //Debug.LogWarning("[UGUIMultiClickButton]: OnDoubleClickEvent");
                    if (onDoubleClickEvent != null) { onDoubleClickEvent(this); }
                    break;

                default:
                    //Debug.LogWarning("[UGUIMultiClickButton]: OnMultiClickEvent: " + _clickCount);
                    if (onMultiClickEvent != null) { onMultiClickEvent(this, _clickCount); }
                    break;
            }

            _clickCount = 0;
            _lastClickTime = 0.0f;
        }
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        _lastClickTime = GetTime();
        _clickCount++;
    }

    private float GetTime()
    {
        return ignoreTimeScale ? Time.fixedTime : Time.time;
    }
}